const app = require("http").createServer();
const io = require("socket.io")(app);

const PORT = 8090;
app.listen(PORT);

let clientCount = 0;
let socketMap = {};

let bindListener = function(socket, events){
    socket.on(events, function(data) {
        if (socket.clientSn % 2 === 0){
            if (socketMap[socket.clientSn - 1]){
                socketMap[socket.clientSn - 1].emit(events, data);
            }
        } else {
            if (socketMap[socket.clientSn + 1]){
                socketMap[socket.clientSn + 1].emit(events, data);
            }
        }
    });
};

io.on("connection", function(socket) {
    clientCount += 1;
    socket.clientSn = clientCount;
    socketMap[clientCount] = socket;
    console.log("user_" + socket.clientSn + " join ...");

    if (clientCount % 2 === 1) {
        socket.emit("waiting", "等待其他用户接入");
    } else {
        if (socketMap[(clientCount - 1)]){
            socket.emit("start");
            socketMap[(clientCount - 1)].emit("start");
        } else {
            socket.emit("leave");
        }
    }

    bindListener(socket, "init");
    bindListener(socket, "next");
    bindListener(socket, "rotate");
    bindListener(socket, "right");
    bindListener(socket, "down");
    bindListener(socket, "left");
    bindListener(socket, "fall");
    bindListener(socket, "fixed");
    bindListener(socket, "line");
    bindListener(socket, "time");
    bindListener(socket, "lose");
    bindListener(socket, "bottomLines");
    bindListener(socket, "addTailLines");

    socket.on("disconnect", function() {
        if (socket.clientSn % 2 === 0){
            if (socketMap[socket.clientSn - 1]){
                socketMap[socket.clientSn - 1].emit("leave");
            }
        } else {
            if (socketMap[socket.clientSn + 1]){
                socketMap[socket.clientSn + 1].emit("leave");
            }
        }
        delete(socketMap[socket.clientSn]);
        clientCount -= 1;
        console.log("user_" + socket.clientSn + " leave ...");
    });
});

console.log("websocket listening on port " + PORT);
